<?php
require_once __DIR__ . '/../../functions.php';

header('Content-Type: application/json');

// 检查管理员权限
if (!isAdmin()) {
    echo json_encode(['success' => false, 'message' => '您没有权限执行此操作']);
    exit;
}

if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    $action = $_POST['action'] ?? '';
    $userIds = $_POST['user_ids'] ?? [];
    
    $db = getDB();
    
    if ($action == 'batch_approve') {
        if (empty($userIds)) {
            echo json_encode(['success' => false, 'message' => '请选择要审批的用户']);
            exit;
        }
        
        // 将用户ID数组转换为逗号分隔的字符串
        $placeholders = str_repeat('?,', count($userIds) - 1) . '?';
        
        $stmt = $db->prepare("UPDATE users SET is_approved = 1, approved_at = NOW(), approved_by = ? WHERE id IN ($placeholders)");
        $params = array_merge([$_SESSION['user_id']], $userIds);
        
        if ($stmt->execute($params)) {
            $count = $stmt->rowCount();
            echo json_encode(['success' => true, 'message' => "批量审批成功，共审批 {$count} 个用户"]);
        } else {
            echo json_encode(['success' => false, 'message' => '批量审批失败']);
        }
    } elseif ($action == 'approve_all') {
        $stmt = $db->prepare("UPDATE users SET is_approved = 1, approved_at = NOW(), approved_by = ? WHERE is_approved = 0");
        if ($stmt->execute([$_SESSION['user_id']])) {
            $count = $stmt->rowCount();
            echo json_encode(['success' => true, 'message' => "一键审批成功，共审批 {$count} 个用户"]);
        } else {
            echo json_encode(['success' => false, 'message' => '一键审批失败']);
        }
    } else {
        echo json_encode(['success' => false, 'message' => '无效的操作类型']);
    }
} else {
    echo json_encode(['success' => false, 'message' => '无效的请求方法']);
}
?>